package com.stockz.downloaderx.callback;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.stockz.core.manager.ScripManager;
import com.stockz.core.model.Bar;
import com.stockz.core.model.Scrip;
import com.stockz.downloaderx.Download;
import com.stockz.downloaderx.Downloader.Callback;

@Component
public class AnalysisCallback implements Callback{
	private static Logger logger = Logger.getLogger(AnalysisCallback.class);
	
	@Autowired
	private ScripManager scripManager;

	public int getOrder() {
		return 100;
	}

	public void execute(Download download) {
		logger.trace(this.getClass().getName()+" called");
		if(download != null && download.getDownloadDate() != null
				&& download.getBarList() != null && !download.getBarList().isEmpty()
				&& download.getEvent() != null && EVENT.PARSE.equals(download.getEvent())
				&& download.getType() != null && TYPE.SUCCESS.equals(download.getType())){
			Scrip scrip = new Scrip();
			scrip.setCode(download.getExchange().getCode());
			scrip.setName(download.getExchange().getName());
			if(!scripManager.getAllScrip().contains(scrip)){
				scripManager.persist(scrip);
			}
			Bar compositBar = new Bar();
			for(Bar bar : download.getBarList()){
				
				compositBar.setCode(download.getExchange().getCode());
				compositBar.setOpen(0);
				compositBar.setHigh(0);
				compositBar.setLow(0);
				compositBar.setClose(0);
				compositBar.setPreviousClose(0);
				compositBar.setLast(0);
				compositBar.setVolume(compositBar.getVolume()+bar.getVolume());
				compositBar.setTurnover(compositBar.getTurnover()+bar.getTurnover());
				compositBar.setTrades(compositBar.getTrades()+bar.getTrades());
			}
			compositBar.setDate(download.getBarList().get(0).getDate());
			download.getBarList().add(compositBar);
		
		}
	}
}